/*******************************************************************************
 * Software Name : Android Simple Downloader
 *
 * Copyright © 2012 Rinvay Tang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package com.rinvay.network.http.conn;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;


import com.rinvay.network.access.NetworkAccess;
import com.rinvay.network.http.HttpRequest;
import com.rinvay.network.http.exception.NetWorkInvalidException;
import com.rinvay.utils.logger.Logger;

/**
 * Http 连接类
 * @author rinvay
 * @date 2012-3-10
 */
public abstract class HttpConnection implements Runnable
{
    private static final String TAG = "HttpConnection";

    private String name = "";

    protected int httpConnectionState = -1;

    protected HttpRequest request = null;

    protected HttpConnectionListener listener = null;

    protected HttpURLConnection conn = null;

    protected InputStream in = null;

    
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * open connection to url
     * @throws MalformedURLException 
     * @throws IOException 
     * @throws NetWorkInvalidException 
     */
    public HttpURLConnection connect() throws MalformedURLException,
            IOException, NetWorkInvalidException {
        Logger.info(TAG, name + " connect");
        if(!NetworkAccess.getInstance().isNetWorkValid()) {
            Logger.info(TAG, "NetWorkInvalid");
           throw new NetWorkInvalidException();
        }
        
        //MalformedURLException: a MalformedURLException may be thrown here 
        URL url = new URL(request.getUrl());

        //a IOException may be thrown here eg:UnknownHostException
        try{
            conn = (HttpURLConnection) url.openConnection();
        } catch(IOException e) {
            e.printStackTrace();
            throw e;
        }
        //a IOException may be thrown here eg:ProtocolException, but it's unusual
        conn.setRequestMethod(request.getMethod());

        //		if ("POST".equalsIgnoreCase(request.getMethod())) {
        conn.setDoInput(true);
        conn.setDoOutput(true);
        //		}

        HashMap<String, String> headers = request.getHeaders();
        if (headers != null) {
            Set<Entry<String, String>> entries = headers.entrySet();
            Iterator<Entry<String, String>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = iterator.next();
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        //IOException: A SocketTimeoutException is thrown if the connection could not be established when connect()
        conn.setConnectTimeout(60 * 1000);
        //IOException  A SocketTimeoutException is thrown if the connection could not be established when connect()
        conn.setReadTimeout(60 * 1000);

        try{
            conn.connect();
        } catch(IOException e) {
            e.printStackTrace();
            throw e;
        }
        Logger.info(TAG, name + " connected");
        return conn;
    }

    /**
     * post data while POST request
     * @param data
     * @throws IOException
     */
    protected void sendData(byte[] data) throws IOException {
        OutputStream os = conn.getOutputStream();
        os.write(data);
        os.flush();
        os.close();
    }

    /**
     * get response inputstream
     * @return
     * @throws IOException
     */
    public InputStream getInputStream() throws IOException {
        in = conn.getInputStream();
        return in;
    }

    /**
     * close stream and connection
     */
    public void close() {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

    }

    /**
     * read byte from inputstream
     * 
     * @param in
     * @return
     * @throws IOException
     */
    protected static byte[] readStream(InputStream in) throws IOException {
        byte[] buffer = new byte[1024 * 4];
        int len = -1;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((len = in.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        byte[] data = baos.toByteArray();
        baos.close();
        return data;
    }

    protected static final int CONNECTION_STATE_CONNECTING = 0;
    protected static final int CONNECTION_STATE_CONNECTED = CONNECTION_STATE_CONNECTING + 1;
    protected static final int CONNECTION_STATE_FINISH = CONNECTION_STATE_CONNECTED + 1;

}
